<template>
  <div class="role-manage-container">

    <div class="role-manage-search">
      <span class="page-title">角色权限列表</span>
      <el-button type="success" size="small" icon="el-icon-plus" @click="handleAddRole"
                 v-if="checkPermissionPoints(1) == 1">添加角色
      </el-button>
    </div>

    <!--角色列表-->
    <div class="role-manage-table">
      <el-table ref="multipleTable" v-loading="listLoading" :data="roleList" border stripe fit
                :row-style="{height:'50px'}"
                :header-row-style="{height:'40px'}">
        <el-table-column label="角色名称" min-width="800px">
          <template slot-scope="scope">
            <span>{{scope.row.className}}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="200px">
          <template slot-scope="{row}">
            <el-button type="primary" size="mini" @click="handleEdit(row)" v-if="checkPermissionPoints(4) == 1">编辑
            </el-button>
            <el-button type="danger" size="mini" @click="handleDelete(row)" v-if="checkPermissionPoints(2) == 1">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--权限添加/编辑-->
    <el-dialog :visible.sync="dialogVisible" :lock-scroll="true" :title="dialogType==='edit'?'角色编辑':'添加角色'"
               width="960px" class="role-opt-dialog" @close="handelCancel" top="11vh">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-position="right" size="medium" label-width="auto"
               class="demo-ruleForm">
        <el-form-item label="角色名称:" prop="className" v-if="dialogType === 'new'">
          <el-input v-model="ruleForm.className" style="width: 640px;" placeholder="请输入角色名称"
                    :clearable="true"></el-input>
        </el-form-item>

        <el-tree
          ref="menuList"
          :data="menuData"
          show-checkbox
          node-key="id"
          :check-strictly="checkStrictly"
          :default-expand-all="expandAll"
          :default-checked-keys="checkedKeys"
          :props="defaultProps">
        </el-tree>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="success" class="dialog-btn-text" @click="handelCheckedNodes">保存</el-button>
        <el-button size="small" class="dialog-btn-text" @click="handelCancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex';
  import {permissionPoints} from '@/utils/permission';
  import {Loading} from 'element-ui';
  import {deleteRole, getInitMenuList, getInitRoleList, modifyRole} from "../../../api/user/user";

  export default {
    name: "roleManage",
    computed: {
      ...mapGetters([
        'points'
      ])
    },
    data() {
      return {
        dialogType: 'new',
        dialogVisible: false,
        listLoading: false,
        roleList: [],
        ruleForm: {
          className: ''
        },
        rules: {
          className: [
            {required: true, message: '请输入角色名称', trigger: 'blur'}
          ]
        },
        menuData: [],
        defaultProps: {
          children: 'menuList',
          label: 'menuName'
        },
        checkStrictly: false,
        expandAll: false,
        checkedKeys: [],
        selectMenuId: [],
        selArr: [],
        permissions: [],
        className: ''
      }
    },
    created() {
      this.getRoleList();
      this.getMenuList();
    },
    methods: {
      checkPermissionPoints(type) {
        let pointObj = this.points.roleManage;
        return permissionPoints(type, pointObj);
      },
      getRoleList() {//获取角色列表
        this.listLoading = true;
        getInitRoleList().then((res) => {
          let retObj = res;
          this.listLoading = false;
          if (retObj.code == 0 && retObj.data!= null) {
            this.roleList = retObj.data;
          }
        }).catch(() => {
          this.listLoading = false;
        })
      },
      getMenuList() {//获取菜单列表
        getInitMenuList(this.className).then((res) => {
          let retObj = res;
          if (retObj.code == 0 && retObj.data!= null) {
            this.menuData = retObj.data;
            if (this.className) {
              this.selectKeys(this.menuData);
              this.checkedKeys = this.selArr;
              this.ruleForm.className = this.className;
            }
          }
        })
      },
      selectKeys(nodeList) {// 查找已经被选中的节点
        for (let menu of nodeList) {
          if (menu.id && menu.menuName && menu.subId == '1') {
            this.selArr.push(menu.id);
          }
          if (menu.menuList && menu.menuList.length > 0) {
            this.selectKeys(menu.menuList)
          }
        }
      },
      handleAddRole() {//添加
        this.dialogType = 'new';
        this.dialogVisible = true;
      },
      handelCancel() {
        this.dialogVisible = false;
        this.$refs.ruleForm.resetFields();
        this.$refs.menuList.setCheckedKeys([]);
      },
      handleEdit(row) {//编辑
        this.dialogType = 'edit';
        this.dialogVisible = true;
        this.className = row.className;
        this.getMenuList();
      },
      handleDelete(row) {
        this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteRole(row.className).then((res) => {
            let retObj = res;
            if (retObj.code == 0) {
              if (retObj.data > 0) {
                this.$message.success({message: '删除角色成功', duration: 2000});
                this.getRoleList();
              } else {
                this.$message.error({message: '删除用户角色失败，请重试', duration: 2000});
              }
            }
          })
        }).catch((err) => {
        });
      },
      handelCheckedNodes() {
        if (this.dialogType === 'new') {
          this.$refs.ruleForm.validate((valid) => {
            if (valid) {
              this.commonTreeSelect();
            } else {
              return false;
            }
          });
        } else {
          this.commonTreeSelect();
        }
      },
      commonTreeSelect() {
        let treeCheckList = [];
        this.selectMenuId = this.$refs.menuList.getCheckedKeys().concat(this.$refs.menuList.getHalfCheckedKeys());//获取选中的nodeId

        let nodeList = this.$refs.menuList.getCheckedNodes().concat(this.$refs.menuList.getHalfCheckedNodes());//获取选中的所有节点数据
        nodeList.forEach(value => {//遍历找出tree节点数据
          for (let i = 0; i < this.selectMenuId.length; i++) {
            if (value.id == this.selectMenuId[i] && value.menuList && value.menuList[0].menuList) {
              treeCheckList.push(value)
            }
          }
        });

        if (treeCheckList && treeCheckList.length > 0) {
          let loading = Loading.service({
            text: '拼命加载中....',
            lock: false,
            background: 'rgba(0, 0, 0, 0.5)'
          });

          treeCheckList.forEach(secondTree => {//遍历二级tree选中的数据
            secondTree.menuList.forEach(threeTree => {
              if (threeTree && threeTree.menuList.length > 0) {
                let tempObj = {};

                threeTree.menuList.forEach(value => {//遍历三级tree树选中的数据
                  for (let j = 0; j < this.selectMenuId.length; j++) {
                    if (value.id == this.selectMenuId[j]) {
                      if (value.menuName == '新增') {
                        tempObj.addStatus = 1;
                      } else if (value.menuName == '删除') {
                        tempObj.delStatus = 1;
                      } else if (value.menuName == '查看') {
                        tempObj.viewStatus = 1;
                      } else if (value.menuName == '修改') {
                        tempObj.editStatus = 1;
                      } else if (value.menuName == '导入') {
                        tempObj.importStatus = 1;
                      } else if (value.menuName == '导出') {
                        tempObj.export = 1;
                      }
                    }
                  }
                });
                threeTree.menuList = [];
                threeTree.addStatus = tempObj.addStatus;
                threeTree.delStatus = tempObj.delStatus;
                threeTree.editStatus = tempObj.editStatus;
                threeTree.viewStatus = tempObj.viewStatus;
                threeTree.export = tempObj.export;
                threeTree.importStatus = tempObj.importStatus;
              }
            });
          });
          this.saveOrUpdateTree(treeCheckList, loading);
        }
      },
      saveOrUpdateTree(tree, loading) {//新增/修改角色权限
        modifyRole(this.ruleForm.className, tree).then((res) => {
          let retObj = res;
          loading.close();
          this.dialogVisible = false;
          if (retObj.code == 0 && retObj.data == 1) {
            let msg = this.dialogType === 'new' ? '新增角色成功' : '修改角色成功';
            this.$message.success({message: msg, duration: 2000});
            this.getRoleList();
          }
        }).catch(() => {
          loading.close();
          this.dialogVisible = false;
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .role-manage-container {
    .role-manage-search {
      display: flex;
      align-items: center;
      width: 100%;
      height: 80px;
      .page-title {
        padding-right: 36px;
        padding-left: 20px;
        font-size: 18px;
        font-weight: bold;
        color: rgba(61, 68, 77, 1);
      }
    }
    .role-manage-table {
      width: 98%;
      margin-left: 18px;
      > > > .el-table td, .el-table th {
        padding: 6px 0px;
      }
      > > > .el-table__header th {
        padding: 0;
        height: 30px;
        line-height: 30px;
      }
      > > > .el-table__fixed-right {
        height: 100% !important;
      }
    }
    .role-opt-dialog > > > .el-dialog .el-dialog__header {
      display: flex;
      align-items: center;
      height: 48px;
      background: #F7F8FA;
      padding: 0px 0px 0px 12px;
      position: fixed;
      width: 960px;
      z-index: 999;
      .el-dialog__headerbtn {
        top: 15px;
      }
    }
    .role-opt-dialog .demo-ruleForm {
      > > > .el-input--medium .el-input__inner {
        background: #F7F8FA;
      }
    }
    .role-opt-dialog > > > .el-dialog {
      overflow-y: auto;
      height: 70%;
    }
    .role-opt-dialog > > > .el-dialog .el-dialog__body {
      margin-top: 48px;
    }
    .dialog-btn-text {
      width: 96px;
    }
    > > > .el-button {
      line-height: 1.2;
    }
  }
</style>
